package com.zbw.printlibrary.printSub;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Handler;

import com.printer.sdk.PrinterConstants;
import com.printer.sdk.PrinterInstance;
import com.printer.sdk.usb.USBPort;
import com.zbw.printlibrary.bean.AttributeBean;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.PrinterControlCommon;
import com.zbw.printlibrary.util.CheckUtil;
import com.zbw.printlibrary.util.PrintThreadPoolManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 天之河-F24A设备打印
 */
public class PrintTianZhiHeF24A extends PrinterControlCommon {
    private Context mContext;
    private IPrintCallBack mCallBack;
    private static final String ACTION_USB_PERMISSION = "com.android.usb.USB_PERMISSION";
    private Handler mHandler = new Handler();
    private PrinterInstance mPrinter;
    private List<UsbDevice> mDeviceList;
    private UsbManager mUsbManager;
    private UsbDevice mUsbDevice;

    public PrintTianZhiHeF24A(Context mContext, IPrintCallBack mCallBack) {
        this.mContext = mContext;
        this.mCallBack = mCallBack;
        initUsbDevice();
    }

    private void initUsbDevice() {
        mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> devices = mUsbManager.getDeviceList();
        mDeviceList = new ArrayList<>();
        for (UsbDevice device : devices.values()) {
            if (USBPort.isUsbPrinter(device)) {
                mDeviceList.add(device);
                break;
            }
        }
    }

    private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    mContext.unregisterReceiver(mUsbReceiver);
                    UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)
                            && mUsbDevice.equals(device)) {
                        realConnect();
                    } else {
                        mCallBack.onConnect("连接失败", false);
                    }
                }
            }
        }
    };

    @Override
    public void connectPrinter() {
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    if (CheckUtil.isEmpty(mDeviceList)) {
                        mCallBack.onConnect("连接失败", false);
                        return;
                    }
                    mUsbDevice = mDeviceList.get(0);
                    mPrinter = PrinterInstance.getPrinterInstance(mContext, mUsbDevice, mHandler);

                    if (mUsbManager.hasPermission(mUsbDevice)) {
                        realConnect();
                    } else {
                        // 没有权限询问用户是否授予权限
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext,
                                0, new Intent(ACTION_USB_PERMISSION), 0);
                        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
                        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
                        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
                        mContext.registerReceiver(mUsbReceiver, filter);
                        mUsbManager.requestPermission(mUsbDevice, pendingIntent);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mCallBack.onConnect("连接失败", false);
                }
            }
        });
    }

    private void realConnect() {
        if (mPrinter.openConnection()) {
            mCallBack.onConnect("连接成功", true);
        } else {
            mCallBack.onConnect("连接失败", false);
        }
    }

    @Override
    public void disConnectPrinter() {
        try {
            mPrinter.closeConnection();
            mCallBack.onDisConnect("断开成功", true);
        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onDisConnect("断开失败", false);
        }
    }

    @Override
    public void printTest(List<String> testList) {
        if (CheckUtil.isEmpty(testList)) {
            mCallBack.onPrintResult(false);
            return;
        }
        try {
            String title = testList.get(0);
            mPrinter.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_CENTER);
            mPrinter.setFont(0, 0, 0, 1, 0);
            mPrinter.printText(title + "\n");
            mPrinter.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_LEFT);
            mPrinter.setFont(0, 0, 0, 0, 0);
            for (int i = 1; i < testList.size(); i++) {
                // 小票主要内容
                mPrinter.printText(testList.get(i) + "\n");
            }
            printLine(mPrinter, 3);
            // 走纸4行,再切纸
            mPrinter.cutPaper(66, 0);

            mCallBack.onPrintResult(true);
        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onPrintResult(false);
        }
    }

    @Override
    public void printString(List<AttributeBean> testList) {
        if (CheckUtil.isEmpty(testList)) {
            mCallBack.onPrintResult(false);
            return;
        }
        try {
            for (int i = 0; i < testList.size(); i++) {
                switch (testList.get(i).getFont_gray()) {
                    case 0:
                        mPrinter.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_LEFT);
                        break;
                    case 1:
                        mPrinter.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_CENTER);
                        break;
                    case 2:
                        mPrinter.setPrinter(PrinterConstants.Command.ALIGN, PrinterConstants.Command.ALIGN_RIGHT);
                        break;
                }
                if (testList.get(i).getFont_size()==2){
                    mPrinter.setFont(0, 0, 0, 1, 0);
                }else{
                    mPrinter.setFont(0, 0, 0, 0, 0);
                }

                String line="";
                if (testList.get(i).isFont_line()){
                    line= "\n";
                }

                // 小票主要内容
                mPrinter.printText(testList.get(i).getContext() + line);
            }
            printLine(mPrinter, 3);
            // 走纸4行,再切纸
            mPrinter.cutPaper(66, 0);

            mCallBack.onPrintResult(true);
        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onPrintResult(false);
        }
    }

    @Override
    public void printStringAndBitmap(List<String> testList, LinkedHashMap<Integer, Bitmap> bitmapHashMap) {
        printTest(testList);
    }

    @Override
    public void blueConnect(String address) {

    }

    @Override
    public void disBlueConnect() {

    }

    @Override
    public void openMoneyBox() {

    }

    @Override
    public boolean isConnected() {
        return mPrinter.openConnection();
    }

    private void printLine(PrinterInstance printer, int line) {
        if (printer == null || line < 0) {
            return;
        }
        try {
            for (int i = 0; i < line; i++) {
                printer.printText("\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void printString(List<AttributeBean> testList, int width) {

    }

}
